import React from 'react';
import {FlatList, Image, StyleSheet, Text, Modal} from 'react-native';
import {TouchableOpacity, View} from 'react-native-ui-lib';
import {commonStyles} from '../../configs/commonStyle';
import BasePage from '../BasePage';
import ListEmpty from '../common/ListEmpty';
import NavigationBar from '../common/NavigationBar';
import ViewUtils from '../../utils/ViewUtils';
import {inject, observer} from 'mobx-react';
import {setClipboardContent} from '../../utils/util';
import {NavigationEvents} from 'react-navigation';
import ImageViewer from 'react-native-image-zoom-viewer';
import { getWorkAskTransportList } from '../../net/seekOrder';
import HandleDialog from './HandleDialog';
import DateFilter from "../components/DateFilter";
import moment from "moment";
import PickerTypeDialog from '../common/PickerTypeDialog';
import {Icon} from '../components';
import { getSeekOrderCount, removeNotification } from '../../plugins/SeekOrderNotification';

const pickerData = ['未处理', '同意', '不同意'];
/**
 * 咨询工单
 */
@inject('userStore', 'appStore')
@observer
export default class SeekOrder extends BasePage {
  constructor(props) {
    super(props);
    this.isLoading = false;
    this.state = {
      isImageShow: false,
      selectIndex: 0,
      images: [],
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      timeStart: moment().format("YYYY-MM-DD"),
      timeEnd: moment().format("YYYY-MM-DD"),
      disposeState: '0',
    };
  }

  componentDidMount() {
    removeNotification()
  }

  loadData(showLoading = false) {
    const { userInfo } = this.props.userStore;
    const { timeStart, timeEnd, disposeState } = this.state;
    this.isLoading = true;
    let params = {
      cityId: userInfo && userInfo.deptId,
      disposeState,
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
      showLoading,
    };
    getWorkAskTransportList(params).then(res => {
      if (res.result && res.result.content) {
        this.setState({
          dataList: res.result.content || [],
          isRefreshing: false,
          showEmpty: IsNullOrEmpty(res.result.content),
        });
      } else {
        this.setState({
          showEmpty: true,
        });
      }
    }).finally(() => {
      this.isLoading = false;
      this.setState({
        isRefreshing: false,
        showEmpty: true,
      });
    });
  }

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.loadData(!isRefreshing);
    }
  };

  showImages = (imageList) => {
    this.setState({
      isImageShow: true,
      images: imageList.map(url => {
        return {url}
      })
    })
  }

  // 处理
  onHandle = (item) => {
    this.handleDialog && this.handleDialog.show(item)
  }

  render_item = ({item, index}) => {
    let imgList = []
    try {
      imgList = JSON.parse(item.extJson).img
    } catch (error) {
    }
    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity
            activeOpacity={1}
            onPress={() => setClipboardContent(item?.xmbzNo)}>
            <Text style={commonStyles.text_black_14}>
              单号：{item?.xmbzNo}
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>工单等级</Text>
            <Text style={commonStyles.text_black_13}>{item?.complaintLevelName}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>平台单号</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.platformOrderId}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>客户联系电话</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.phone}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>业务类型</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.typeName}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>协助内容</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.content}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>图片附图</Text>
            <View style={commonStyles.text_black_13}>
              {
                imgList && imgList.length ?
                (<TouchableOpacity
                  activeOpacity={1}
                  onPress={() => this.showImages(imgList)}>
                    {
                      imgList.map(item => {
                        return (<Image source={{uri: item}} style={{width: 90, height: 90, marginBottom: 2}}></Image>)
                      })
                    }
                </TouchableOpacity>)
                : null
              }
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理状态</Text>
            <Text style={commonStyles.text_black_13}>{pickerData[item.disposeState] || '-'}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理反馈内容</Text>
            {
              item.disposeState != 0 ? 
              (<Text style={commonStyles.text_black_13}>{item?.resultContent}</Text>) :
              null
            }
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>催办状态</Text>
            <Text style={commonStyles.text_black_13}>{item?.reminder ? '已催办' : '-'}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>创建人</Text>
            <Text style={commonStyles.text_black_13}>{item?.operator}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>创建时间</Text>
            <Text style={commonStyles.text_black_13}>{item?.createTime}</Text>
          </View>
        </View>
        <View style={styles.line} />
        <View style={styles.reasonWrap}>
          <View right>
            {
              item.disposeState == 0 ? 
              (<TouchableOpacity
                activeOpacity={1}
                throttleTime={1000}
                style={styles.btn}
                onPress={() => this.onHandle(item)}>
                <Text style={commonStyles.text_black}>处理</Text>
              </TouchableOpacity>) : null
            }
          </View>
        </View>
      </View>
    );
  };

  render() {
    const {dataList, isRefreshing, disposeState} = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationEvents onDidFocus={() => this._renderRefresh(false)} />
        <NavigationBar
          title={'咨询工单'}
          backgroundColor={'transparent'}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
        />
        <View style={commonStyles.container}>
          <View row centerV style={{flexWrap: 'wrap'}}>
            <DateFilter onQueryClick={(timeStart, timeEnd) => this.setState({
              timeStart,
              timeEnd,
            }, () => this._renderRefresh(false))} />
            <TouchableOpacity
              activeOpacity={1}
              style={styles.typeWrap}
              onPress={() =>
                this.pickerOrderTypeDialog && this.pickerOrderTypeDialog.show(disposeState, pickerData)
              }>
              <View marginR-3>
                <Text numberOfLines={1} style={commonStyles.text_black}>
                  {pickerData[disposeState]}
                </Text>
              </View>
              <Icon type="AntDesign" name="down" size={12} color={'#CCCCCC'} />
            </TouchableOpacity>
            <TouchableOpacity
              activeOpacity={1}
              throttleTime={1000}
              style={{...styles.btn, marginLeft: 10}}
              onPress={() => this._renderRefresh(false)}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{flexGrow: 1}}
            keyExtractor={(item, index) => 'menu_' + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => (
              <ListEmpty showEmpty={this.state.showEmpty} />
            )}
          />
        </View>
        {this.state.isImageShow ? (
          <Modal
            visible={true}
            transparent={true}
            onRequestClose={() => {
              this.setState({
                isImageShow: false,
              });
            }}>
            <ImageViewer
              imageUrls={this.state.images}
              onClick={() => {
                this.setState({
                  isImageShow: false,
                });
              }}
              renderImage={r => (
                <Image style={r.style} source={r.source} resize={'resize'} />
              )}
              index={this.state.selectIndex}
              saveToLocalByLongPress={false}
            />
          </Modal>
        ) : null}

        <HandleDialog ref={dialog => this.handleDialog = dialog} callback={() => {
          this.loadData(true);
          getSeekOrderCount();
        }}></HandleDialog>
        <PickerTypeDialog
          ref={r => (this.pickerOrderTypeDialog = r)}
          onChecked={disposeState => {
            this.setState({disposeState});
            this._renderRefresh(false);
          }}></PickerTypeDialog>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: '#F9D63B',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
  },
  line: {
    height: 1,
    backgroundColor: '#EFEFEF',
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
  typeWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    width: 90,
    height: 40,
    justifyContent: 'space-between',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    paddingHorizontal: 10,
    backgroundColor: 'white',
    marginRight: 10,
  },
});
